package com.hengpeng.itfinoss.controller.borrowinfo;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.util.BeanClone;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.BorrowStatus;
import com.hengpeng.itfinbase.en.DurationType;
import com.hengpeng.itfinbase.en.InputStatus;
import com.hengpeng.itfinbase.en.InvestStatus;
import com.hengpeng.itfinbase.message.partner.AddBidInfoRequest;
import com.hengpeng.itfinbase.message.partner.LoansRequest;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.UsrUnFreezeRequest;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.controller.vo.BorrowInfoVo;
import com.hengpeng.itfinoss.service.GuarantorManager;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.DateTimeUtil;
import com.hengpeng.itfinoss.util.InvestUtils;
import com.hengpeng.itfinoss.util.PropertyClone;
import com.hengpeng.itfinoss.util.StringUtils;

/**
 * 标的信息管理
 * 
 * @author weiyuan
 */
@Controller
@RequestMapping("/borrowInfo")
public class BorrowInfoController extends BaseController {
    public final static Log logger = LogFactory.getLog(BorrowInfoController.class);

    @Autowired
    private ServiceFactory serviceFactory;

    private final static ExecutorService execute = Executors.newCachedThreadPool();

    @PreDestroy
    public void release() {
        if (execute != null) {
            execute.shutdown();
        }
    }

    /**
     * <pre>
     * 标的列表
     * </pre>
     * 
     * @param map
     * @param request
     * @param borrowName
     * @param borrowUserName
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(ModelMap map, HttpServletRequest request, String borrowName, String borrowUserName,
            String startTime, String endTime) {
        map.put("borrowName", borrowName);
        map.put("borrowUserName", borrowUserName);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        Pagination page = new Pagination(request);
        page.setPageSize(this.getPageSize(request));
        Date start = null;
        Date end = null;
        try {
            if (!StringHelper.isEmpty(startTime)) {
                start = StringHelper.getDateFromString(startTime, "yyyy-MM-dd HH:mm");
            }
            if (!StringHelper.isEmpty(endTime)) {
                end = StringHelper.getDateFromString(endTime, "yyyy-MM-dd HH:mm");
            }
            List<BorrowInfo> borrowList = serviceFactory
                    .getBorrowInfoService()
                    .queryList(borrowName, borrowUserName, start, end, new BorrowStatus[] { BorrowStatus.WAITING },
                            null,page.currentPage, page.pageSize).getReturnValue();
            Long count = serviceFactory.getBorrowInfoService()
                    .queryCount(borrowName, borrowUserName, start, end, new BorrowStatus[] { BorrowStatus.WAITING }, null)
                    .getReturnValue();
            List<BorrowInfoVo> list = new ArrayList<BorrowInfoVo>();
            for (BorrowInfo borrowInfo : borrowList) {
                BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
                vo.setBorrowDurationDec(
                        borrowInfo.getBorrowDuration() + (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
                                + borrowInfo.getDurType().getText());
                vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
                // vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
                // vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
                // vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
                list.add(vo);
            }
            page.setEntityCount(count.intValue());
            map.put("borrowList", list);
            map.put("borrowListPage", page);
            return "borrowInfo/borrowInfoList";
        } catch (Exception e) {
            logger.error(e);
            return returnError(map, e);
        }
    }

    /**
     * <pre>
     * 待排期标的
     * </pre>
     * 
     * @param map
     * @param request
     * @param status
     * @param borrowName
     * @param borrowUserName
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "/runList/{status}")
    public String runList(ModelMap map, HttpServletRequest request, @PathVariable BorrowStatus status,
            String borrowName, String borrowUserName, String startTime, String endTime, String inputStatusFlag) {
        map.put("borrowName", borrowName);
        map.put("borrowUserName", borrowUserName);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("status", status);
        Pagination page = new Pagination(request);
        page.setPageSize(this.getPageSize(request));
        Date start = null;
        Date end = null;
        InputStatus[] inputStatus = null;
        BorrowStatus[] borrowStatus = new BorrowStatus[] { status };
        try {
            if (!StringHelper.isEmpty(startTime)) {
                start = StringHelper.getDateFromString(startTime, "yyyy-MM-dd HH:mm");
            }
            if (!StringHelper.isEmpty(endTime)) {
                end = StringHelper.getDateFromString(endTime, "yyyy-MM-dd HH:mm");
            }
            if ("failed".equals(inputStatusFlag)) {
                inputStatus = new InputStatus[] { InputStatus.FAILED };
                borrowStatus = null;
            } else if (BorrowStatus.RAISE.equals(status) || "success".equals(inputStatusFlag)) { // 募集中的标
                                                                                                 // inputStatus要success
                inputStatus = new InputStatus[] { InputStatus.SUCCESS };
            }
            
            List<BorrowInfo> borrowList = serviceFactory.getBorrowInfoService().queryList(borrowName, borrowUserName,
                    start, end, borrowStatus, inputStatus, page.currentPage, page.pageSize).getReturnValue();
            Long count = serviceFactory.getBorrowInfoService()
                    .queryCount(borrowName, borrowUserName, start, end, borrowStatus, inputStatus).getReturnValue();
            List<BorrowInfoVo> list = new ArrayList<BorrowInfoVo>();
            for (BorrowInfo borrowInfo : borrowList) {
                BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
                vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
                        + (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
                        + borrowInfo.getDurType().getText());
                vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
                vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
                vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
                vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
                vo.setRaiseMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getRaiseMoney()));
                list.add(vo);
            }
            page.setEntityCount(count.intValue());
            map.put("inputStatusFlag", inputStatusFlag);
            map.put("borrowList", list);
            map.put("borrowListPage", page);
            return "borrowInfo/runList";
        } catch (Exception e) {
            logger.error(e);
            return returnError(map, e);
        }
    }

    /**
     * <pre>
     * 筹款结束标的
     * </pre>
     * 
     * @param map
     * @param request
     * @param borrowName
     * @param borrowUserName
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "/end")
    public String end(ModelMap map, HttpServletRequest request, String borrowName, String borrowUserName,
            String startTime, String endTime) {
        map.put("borrowName", borrowName);
        map.put("borrowUserName", borrowUserName);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        Pagination page = new Pagination(request);
        page.setPageSize(this.getPageSize(request));
        Date start = null;
        Date end = null;
        try {
            if (!StringHelper.isEmpty(startTime)) {
                start = StringHelper.getDateFromString(startTime, "yyyy-MM-dd HH:mm");
            }
            if (!StringHelper.isEmpty(endTime)) {
                end = StringHelper.getDateFromString(endTime, "yyyy-MM-dd HH:mm");
            }
            BorrowStatus[] status = new BorrowStatus[] { BorrowStatus.END, BorrowStatus.LOANING, BorrowStatus.LOSSING };
            List<BorrowInfo> borrowList = serviceFactory.getBorrowInfoService()
                    .queryList(borrowName, borrowUserName, start, end, status,null, page.currentPage, page.pageSize)
                    .getReturnValue();
            Long count = serviceFactory.getBorrowInfoService()
                    .queryCount(borrowName, borrowUserName, start, end, status,null).getReturnValue();
            List<BorrowInfoVo> list = new ArrayList<BorrowInfoVo>();
            for (BorrowInfo borrowInfo : borrowList) {
                BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
                vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
                        + (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
                        + borrowInfo.getDurType().getText());
                vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
                vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
                vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
                vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
                vo.setRaiseMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getRaiseMoney()));
                list.add(vo);
            }
            page.setEntityCount(count.intValue());
            map.put("borrowList", list);
            map.put("borrowListPage", page);
            return "borrowInfo/end";
        } catch (Exception e) {
            logger.error(e);
            return returnError(map, e);
        }
    }

    /**
     * <pre>
     * 截止标的
     * </pre>
     * 
     * @param map
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/doEnd/{id}")
    public String doEnd(ModelMap map, HttpServletRequest request, @PathVariable Long id) {

        List<InvestInfo> l = serviceFactory.getInvestInfoService().getInvestInfos(id,
                new InvestStatus[] { InvestStatus.INVESTING });
        if (l != null && l.size() > 0) {
            return returnError(map, "该标的有投标中的记录,不能截止");
        }
        BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
        borrow.setStatus(BorrowStatus.END);
        serviceFactory.getPersistService().update(borrow);
        return PageHandlerUtil.returnSuccess(map, "截止成功！", "/borrowInfo/runList/RAISE");
    }

    /**
     * <pre>
     * 跳转标的排期
     * </pre>
     * 
     * @param id
     * @param map
     * @return
     */
    @RequestMapping(value = "/preschedule/{id}")
    public String preSchedule(@PathVariable Long id, ModelMap map) {
        try {
            BorrowInfo borrowInfo = serviceFactory.getPersistService().get(BorrowInfo.class, id);
            BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
            vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
                    + (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
                    + borrowInfo.getDurType().getText());
            vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
            vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
            vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
            vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
            vo.setRaiseMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getRaiseMoney()));
            map.put("borrowInfo", vo);
            return "borrowInfo/schedule";
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    /**
     * <pre>
     * 标的排期
     * </pre>
     * 
     * @param id
     * @param bidOpenTime
     * @param map
     * @return
     */
    @RequestMapping(value = "/schedule", method = RequestMethod.POST)
    public String schedule(Long id, String bidOpenTime, ModelMap map) {
        if (StringHelper.isEmpty(bidOpenTime)) {
            return PageHandlerUtil.returnError(map, "未选定开标时间!");
        }
        try {
            if (new SimpleDateFormat("yyyy-MM-dd hh:mm").parse(bidOpenTime).before(new Date())) {
                return PageHandlerUtil.returnError(map, "开标时间不能小于当前时间!");
            }
        } catch (ParseException e) {
            return PageHandlerUtil.returnError(map, "系统异常，请重试!");
        }
        try {
            final BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
            borrow.setBidOpenTime(StringHelper.getDateFromString(bidOpenTime, "yyyy-MM-dd HH:mm"));
            borrow.setBidStopTime(DateTimeUtil.addHour(borrow.getBidOpenTime(), borrow.getRaiseDuration()));
            borrow.setStatus(BorrowStatus.SCHEDULED);
            borrow.setInputStatus(InputStatus.WAIT);
            serviceFactory.getPersistService().update(borrow);
            execute.execute(new Runnable() {
                @Override
                public void run() {
                    AddBidInfoRequest addRequest = new AddBidInfoRequest();
                    addRequest.setPartnerTransType(PartnerTransType.AddBidInfo);
                    addRequest.setProId(borrow.getId().toString());
                    addRequest.setBidStartDate(StringHelper.getStringFromDate(borrow.getBidOpenTime(), "yyyyMMddhhmmss"));
                    addRequest.setBidEndDate(StringHelper.getStringFromDate(borrow.getBidStopTime(), "yyyyMMddhhmmss"));
                    addRequest.setBorrCustId(borrow.getBorrowUserTrustAccountId());
                    addRequest.setBorrTotAmt(MoneyUtil.convertFenToYuan(borrow.getBorrowMoney()));
                    addRequest.setYearRate(new DecimalFormat("#.00").format((borrow.getBorrowRate() + borrow
                            .getRewardRate())));
                    addRequest.setGuarCompId(borrow.getGuaranteeUserTrustAccountId());
                    Double guarAmt = borrow.getBorrowMoney() * borrow.getGuaranteeFeeRate() / 100;// 担保费用
                    addRequest.setGuarAmt(MoneyUtil.convertFenToYuan(guarAmt.longValue()));
                    addRequest.setProArea("4402");// 区域深圳
                    Date end = null;
                    switch (borrow.getRepaymentType()) {
                    case EQUALINTEREST:
                        long month = InvestUtils.equalInterest(borrow.getBorrowMoney(),
                                (borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration());
                        end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(), Calendar.MONTH);
                        addRequest.setRetAmt(MoneyUtil.convertFenToYuan(month * borrow.getBorrowDuration()));
                        addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
                        addRequest.setRetType("01");
                        break;
                    case EQUALPRINCIPAL:
                        long total = InvestUtils.equalPrincipal(borrow.getBorrowMoney(),
                                (borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration());// 等额本金还款总额
                        end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(), Calendar.MONTH);
                        addRequest.setRetAmt(MoneyUtil.convertFenToYuan(total));
                        addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
                        addRequest.setRetType("02");
                        break;
                    case MONTHINTEREST:// 按月付息到期还本
                        if (borrow.getDurType().equals(DurationType.MONTH)) {
                            end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
                                    Calendar.MONTH);
                        } else {
                            end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
                                    Calendar.DATE);
                        }
                        long interest = InvestUtils.rtcapitalInterest(borrow.getBorrowMoney(),
                                (borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration(),
                                borrow.getDurType());
                        addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
                        addRequest.setRetAmt(MoneyUtil.convertFenToYuan(interest + borrow.getBorrowMoney()));
                        addRequest.setRetType("03");
                        break;
                    case RTCAPITALINTEREST:// 一次性还本付息
                        if (borrow.getDurType().equals(DurationType.MONTH)) {
                            end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
                                    Calendar.MONTH);
                        } else {
                            end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
                                    Calendar.DATE);
                        }
                        long rest = InvestUtils.rtcapitalInterest(borrow.getBorrowMoney(),
                                (borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration(),
                                borrow.getDurType());
                        addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
                        addRequest.setRetAmt(MoneyUtil.convertFenToYuan(rest + borrow.getBorrowMoney()));
                        addRequest.setRetType("04");
                        break;
                    }
                    addRequest.setTransType(TransCodeConstants.BidTransCode.BID_ADDBIDINFO_REQUEST);
                    addRequest.setBgRetUrl(service_notify_url);
                    addRequest.setRetUrl(page_return_url);
                    serviceFactory.getRemoteService().remoteTrans(addRequest);
                }
            });
            return PageHandlerUtil.returnSuccess(map, "标的排期成功", "/borrowInfo/runList/" + BorrowStatus.PASS);
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    /**
     * <pre>
     * 放款操作
     * </pre>
     * 
     * @param id
     * @param map
     * @return
     */
    @RequestMapping(value = "/loan/{id}")
    public String loan(@PathVariable Long id, ModelMap map) {
        try {
            BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
            if (borrow != null) {
                if (borrow.getStatus().equals(BorrowStatus.END) || borrow.getStatus().equals(BorrowStatus.LOANING)) {
                    LoansRequest request = new LoansRequest();
                    request.setBorrowId(id);
                    request.setTransType(TransCodeConstants.BidTransCode.BID_LOANS_REQUEST);
                    request.setBgRetUrl(service_notify_url);
                    request.setRetUrl(page_return_url);
                    serviceFactory.getRemoteService().remoteTrans(request);
                    return PageHandlerUtil.returnSuccess(map, "放款操作成功！", "/borrowInfo/end");
                } else {
                    return PageHandlerUtil.returnError(map, "标的状态为" + borrow.getStatus().getText() + ",不允许放款！");
                }
            } else {
                return PageHandlerUtil.returnError(map, "放款失败，不存在的标的编号:" + id);
            }
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    /**
     * <pre>
     * 流标操作
     * </pre>
     * 
     * @param id
     * @param map
     * @return
     */
    @RequestMapping(value = "/loss/{id}")
    public String loss(@PathVariable Long id, ModelMap map) {
        try {
            try {
                BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
                if (borrow != null) {
                    if (borrow.getStatus().equals(BorrowStatus.END) || borrow.getStatus().equals(BorrowStatus.LOSSING)) {
                        UsrUnFreezeRequest request = new UsrUnFreezeRequest();
                        request.setBorrowId(id);
                        request.setTransType(TransCodeConstants.BidTransCode.BID_LOSS_REQUEST);
                        request.setBgRetUrl(service_notify_url);
                        request.setRetUrl(page_return_url);
                        serviceFactory.getRemoteService().remoteTrans(request);
                        return PageHandlerUtil.returnSuccess(map, "流标操作成功！", "/borrowInfo/end");
                    } else {
                        return PageHandlerUtil.returnError(map, "标的状态为" + borrow.getStatus().getText() + ",不允许流标！");
                    }
                } else {
                    return PageHandlerUtil.returnError(map, "放款失败，不存在的标的编号:" + id);
                }

            } catch (Exception ex) {
                logger.error(ex);
                return PageHandlerUtil.returnError(map, ex);
            }
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String preCreate(ModelMap map) {
        List<UserInfo> guartors = serviceFactory.getUserInfoService().getGuartors();
        List<UserInfo> borrowUser = serviceFactory.getUserInfoService().findUserInfoByType(UserInfoType.ENTERPRISE);
        if (guartors != null && guartors.size() > 0) {
            GuarantorManager.addCache(guartors);
            map.put("guartors", guartors);
            if (borrowUser != null && borrowUser.size() > 0) {
                map.put("borrowUser", borrowUser);
            } else {
                return PageHandlerUtil.returnError(map, "没有借款用户不能发布借款申请!");
            }
            return "borrowInfo/addborrowInfo";
        } else {
            return PageHandlerUtil.returnError(map, "没有担保企业用户不能发布借款申请!");
        }
    }

    @RequestMapping(value = "/get/{id}")
    public String get(@PathVariable Long id, ModelMap map) {
        BorrowInfo obj = serviceFactory.getPersistService().get(BorrowInfo.class, id);
        List<UserInfo> guartors = serviceFactory.getUserInfoService().getGuartors();
        if (guartors != null && guartors.size() > 0) {
            GuarantorManager.addCache(guartors);
            obj.setBorrowMoney(MoneyUtil.convertLongFenToYuan(obj.getBorrowMoney()));
            // obj.setMinInvest(MoneyUtil.convertLongFenToYuan(obj.getMinInvest()));
            // obj.setMaxInvest(MoneyUtil.convertLongFenToYuan(obj.getMaxInvest()));
            // obj.setIncMoney(MoneyUtil.convertLongFenToYuan(obj.getIncMoney()));
            obj.setRaiseMoney(MoneyUtil.convertLongFenToYuan(obj.getRaiseMoney()));
            map.put("borrowInfo", obj);
            map.put("guartors", guartors);
            return "borrowInfo/updateborrowInfo";
        } else {
            return PageHandlerUtil.returnError(map, "没有担保企业用户不能修改借款申请!");
        }
    }

    /**
     * <pre>
     * 新增标的
     * </pre>
     * 
     * @param request
     * @param borrow
     * @param map
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(HttpServletRequest request, BorrowInfo borrow, ModelMap map) {
        try {
            // 页面删除 附加利率 借款服务费率 借款担保费率 避免放生空指针异常，直接set为0.0
            borrow.setRewardRate(0.0);
            borrow.setBorrowFeeRate(0.0);
            borrow.setGuaranteeFeeRate(0.0);
            
            
            UserInfo userInfo = serviceFactory.getUserInfoService().getByUserName(borrow.getBorrowUserName());
            if (userInfo == null) {
                return PageHandlerUtil.returnError(map, "不存在的借款用户");
            }
            if (StringHelper.isEmpty(userInfo.getTrustAccountId())) {
                return PageHandlerUtil.returnError(map, "借款用户还未开通托管账户");
            }
            if (borrow.getBorrowName().length() > 50) {
                return PageHandlerUtil.returnError(map, "标的名称不能大于50个字符");
            }
            UserInfo guar = GuarantorManager.getGuarantor(borrow.getGuaranteeUserId());
            borrow.setBorrowUserId(userInfo.getId());
            borrow.setIsMakeReceivePlan(BoolValue.NO);
            borrow.setIsMakeRepayPlan(BoolValue.NO);
            borrow.setBorrowUserTrustAccountId(userInfo.getTrustAccountId());
            borrow.setGuaranteeRealName(guar.getRealName());
            borrow.setGuaranteeUserTrustAccountId(guar.getTrustAccountId());
            borrow.setStatus(BorrowStatus.WAITING);
            borrow.setInputStatus(InputStatus.WAIT);
            borrow.setRaiseNum(0);
            borrow.setRaiseMoney(0L);
            borrow.setCreateTime(new Date());
            borrow.setBorrowMoney(borrow.getBorrowMoney() * 100);
            borrow.setMinInvest(borrow.getMinInvest() * 100);
            borrow.setMaxInvest(borrow.getMaxInvest() * 100);
            borrow.setIncMoney(borrow.getIncMoney() * 100);
            serviceFactory.getPersistService().save(borrow);
            return PageHandlerUtil.returnSuccess(map, "新增标的成功", "/borrowInfo/list");
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    /**
     * <pre>
     * 修改标的
     * </pre>
     * 
     * @param request
     * @param vo
     * @param map
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public String modify(HttpServletRequest request, BorrowInfo vo, ModelMap map) {
        try {
            BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, vo.getId());
            borrow.setGuaranteeRealName(GuarantorManager.getGuarantor(vo.getGuaranteeUserId()).getRealName());
            UserInfo userInfo = serviceFactory.getUserInfoService().getByUserName(vo.getBorrowUserName());
            if (userInfo == null) {
                return PageHandlerUtil.returnError(map, "不存在的借款用户");
            }
            UserInfo guar = GuarantorManager.getGuarantor(vo.getGuaranteeUserId());
            borrow.setBorrowUserId(userInfo.getId());
            borrow.setIsMakeReceivePlan(BoolValue.NO);
            borrow.setIsMakeRepayPlan(BoolValue.NO);
            borrow.setBorrowUserTrustAccountId(userInfo.getTrustAccountId());
            borrow.setGuaranteeRealName(guar.getRealName());
            borrow.setGuaranteeUserTrustAccountId(guar.getTrustAccountId());
            PropertyClone.copyProperties(borrow, vo, false);
            borrow.setUpdateTime(new Date());
            borrow.setBorrowMoney(borrow.getBorrowMoney() * 100);
            borrow.setMinInvest(borrow.getMinInvest() * 100);
            borrow.setMaxInvest(borrow.getMaxInvest() * 100);
            borrow.setIncMoney(borrow.getIncMoney() * 100);
            if (BorrowStatus.UNPASS.equals(borrow.getStatus())) { // 审核不通过的标状态变更为待审核
                borrow.setStatus(BorrowStatus.WAITING);
            }
            serviceFactory.getPersistService().update(borrow);
            return PageHandlerUtil.returnSuccess(map, "修改标的成功", "/borrowInfo/list");
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    @RequestMapping(value = "/preExamine/{id}")
    public String preExamine(@PathVariable Long id, ModelMap map) {
        try {
            BorrowInfo borrowInfo = serviceFactory.getPersistService().get(BorrowInfo.class, id);
            BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
            vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
                    + (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
                    + borrowInfo.getDurType().getText());
            vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
            vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
            vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
            vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
            map.put("borrowInfo", vo);
            return "borrowInfo/examine";
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    @RequestMapping(value = "/examine/{id}/{status}", method = RequestMethod.POST)
    public String examine(@PathVariable Long id, @PathVariable BorrowStatus status, ModelMap map) {
        try {
            BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
            borrow.setStatus(status);
            borrow.setUpdateTime(new Date());
            serviceFactory.getPersistService().update(borrow);
            return PageHandlerUtil.returnSuccess(map, "审核标的成功", "/borrowInfo/list");
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable Long id, HttpServletRequest request, ModelMap map) {
        try {
            BorrowInfo borrowInfo = serviceFactory.getPersistService().get(BorrowInfo.class, id);
            BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
            vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
                    + (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
                    + borrowInfo.getDurType().getText());
            vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
            vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
            vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
            vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
            map.put("borrowInfo", vo);
            Pagination page = new Pagination(request);
            page.setPageSize(this.getPageSize(request));
            List<InvestInfo> investList = serviceFactory.getBorrowInfoService()
                    .queryInvestList(id, page.currentPage, page.pageSize).getReturnValue();
            for (InvestInfo investInfo : investList) {
                investInfo.setInvestMoney(MoneyUtil.convertLongFenToYuan(investInfo.getInvestMoney()));
            }
            Long count = serviceFactory.getBorrowInfoService().queryInvestCount(id).getReturnValue();
            page.setEntityCount(count.intValue());
            map.put("investList", investList);
            map.put("investListPage", page);
            return "borrowInfo/detail";
        } catch (Exception ex) {
            logger.error(ex);
            return PageHandlerUtil.returnError(map, ex);
        }
    }

}
